package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Banner;
import cn.wolfcode.wolf2w.query.BannerQuery;
import cn.wolfcode.wolf2w.repository.BannerRepository;
import cn.wolfcode.wolf2w.service.IBannerService;
import cn.wolfcode.wolf2w.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
//@Transactional mongodb事务必须复制集方式
public class BannerServiceImpl implements IBannerService {

    @Autowired
    private BannerRepository repository;

    @Autowired
    private MongoTemplate template;


    @Override
    public void save(Banner banner) {
        banner.setId(null);
        repository.save(banner);
    }

    @Override
    public void update(Banner banner) {
        repository.save(banner);
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }

    @Override
    public Banner get(String id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public List<Banner> list() {
        return repository.findAll();
    }

    @Override
    public Page<Banner> query(BannerQuery qo) {
        Query query = new Query();
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(),
                Sort.Direction.ASC, "_id");
        return DBHelper.query(template,pageable,query,Banner.class,qo);
    }

    @Override
    public void saveOrUpdate(Banner banner) {

        if(StringUtils.hasLength(banner.getId())){
            //update
            //特殊案例, 页面更新的数据, 刚好跟集合中字段个数一致
            //所以这种等价于全量更新
            this.update(banner);
        }else{
            //save
            this.save(banner);
        }
    }


    @Override
    public List<Banner> queryBanner(int type) {

        //正常状态和类型,缺一不可
        //必须能显示 , 按照序号排序, 前面5个
        Pageable pageable = PageRequest.of(0, 5, Sort.Direction.ASC, "sequence");

        return  repository.findByStateAndType(Banner.STATE_NORMAL, type, pageable);
    }
}
